/*
 * Created by JFormDesigner on Fri Apr 30 11:59:06 CST 2021
 */

package com.aivin.firplugin.view;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.aivin.firplugin.bean.Apps;
import com.aivin.firplugin.httplib.HttpRespondCallback;
import com.aivin.firplugin.httplib.NetTool;
import com.aivin.firplugin.myconfig.IpConfig;
import com.aivin.firplugin.tool.*;
import com.alibaba.fastjson.JSON;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vfs.VirtualFile;
import net.miginfocom.swing.*;
import java.util.List;


public class ApkInfoPanel {
    public ApkInfoPanel() {
        initComponents();
        getData(currentPage) ; // init
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        ResourceBundle bundle = ResourceBundle.getBundle("com.aivin.firplugin.myconfig.KeySave");
        apkInfoPanel = new JPanel();
        infoShow = new JLabel();
        label4 = new JLabel();
        apitokenFiled = new JTextField();
        getAppsBtn = new JButton();
        scrollPane3 = new JScrollPane();
        applistABC = new JList();
        appSum = new JLabel();
        selectedProgram = new JLabel();
        label2 = new JLabel();
        selectApkBtn = new JButton();
        label3 = new JLabel();
        scrollPane2 = new JScrollPane();
        updateLog = new JTextArea();

        //======== apkInfoPanel ========
        {
            apkInfoPanel.setForeground(Color.pink);
            apkInfoPanel.setBackground(new Color(69, 73, 74));
            apkInfoPanel.setLayout(new MigLayout(
                "hidemode 3",
                // columns
                "[78,fill]" +
                "[637,fill]" +
                "[0,fill]",
                // rows
                "[]" +
                "[]" +
                "[]" +
                "[203]" +
                "[]0" +
                "[]" +
                "[]" +
                "[171]" +
                "[]"));

            //---- infoShow ----
            infoShow.setText(bundle.getString("ApkInfoPanel.infoShow.text"));
            infoShow.setOpaque(true);
            infoShow.setHorizontalAlignment(SwingConstants.CENTER);
            infoShow.setForeground(Color.red);
            apkInfoPanel.add(infoShow, "cell 1 1,grow");

            //---- label4 ----
            label4.setText(bundle.getString("ApkInfoPanel.label4.text"));
            label4.setHorizontalAlignment(SwingConstants.CENTER);
            label4.setForeground(Color.red);
            label4.setOpaque(true);
            apkInfoPanel.add(label4, "cell 0 2");
            apkInfoPanel.add(apitokenFiled, "cell 1 2");

            //---- getAppsBtn ----
            getAppsBtn.setText(bundle.getString("ApkInfoPanel.getAppsBtn.text"));
            getAppsBtn.setBackground(new Color(242, 242, 242));
            getAppsBtn.setOpaque(false);
            apkInfoPanel.add(getAppsBtn, "cell 0 3,growy");

            //======== scrollPane3 ========
            {
                scrollPane3.setViewportView(applistABC);
            }
            apkInfoPanel.add(scrollPane3, "cell 1 3,growy");

            //---- appSum ----
            appSum.setText(bundle.getString("ApkInfoPanel.appSum.text"));
            appSum.setHorizontalAlignment(SwingConstants.CENTER);
            appSum.setOpaque(true);
            appSum.setForeground(Color.red);
            apkInfoPanel.add(appSum, "cell 0 4,growx");

            //---- selectedProgram ----
            selectedProgram.setText(bundle.getString("ApkInfoPanel.selectedProgram.text"));
            selectedProgram.setForeground(Color.red);
            selectedProgram.setOpaque(true);
            selectedProgram.setBackground(new Color(204, 204, 255));
            selectedProgram.setVerticalAlignment(SwingConstants.TOP);
            selectedProgram.setAlignmentY(0.0F);
            selectedProgram.setHorizontalAlignment(SwingConstants.CENTER);
            apkInfoPanel.add(selectedProgram, "cell 1 4,grow");

            //---- label2 ----
            label2.setText(bundle.getString("ApkInfoPanel.label2.text"));
            label2.setOpaque(true);
            label2.setHorizontalAlignment(SwingConstants.CENTER);
            label2.setForeground(Color.red);
            apkInfoPanel.add(label2, "cell 0 6,growx");

            //---- selectApkBtn ----
            selectApkBtn.setText(bundle.getString("ApkInfoPanel.selectApkBtn.text"));
            apkInfoPanel.add(selectApkBtn, "cell 1 6");

            //---- label3 ----
            label3.setText(bundle.getString("ApkInfoPanel.label3.text"));
            label3.setOpaque(true);
            label3.setHorizontalAlignment(SwingConstants.CENTER);
            label3.setForeground(Color.red);
            apkInfoPanel.add(label3, "cell 0 7,grow");

            //======== scrollPane2 ========
            {

                //---- updateLog ----
                updateLog.setTabSize(10);
                updateLog.setText("\u672c\u6b21\u66f4\u65b0\uff1a \n1\u3001 \n2\u3001");
                scrollPane2.setViewportView(updateLog);
            }
            apkInfoPanel.add(scrollPane2, "cell 1 7 2 2,grow");
        }
        // JFormDesigner - End of component initialization  //GEN-END:initComponents


        applistABC.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                boolean isClick = e.getValueIsAdjusting();
                if(!isClick){
                    return;
                }
                String msg = (String) applistABC.getSelectedValue() ;
                selectedProgram.setText(msg);
                selectedApp   = appList.get(applistABC.getSelectedIndex()) ;
            }
        });

        selectApkBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                FileType type = FileTypeManager.getInstance().getFileTypeByExtension("apk");
                FileChooserDescriptor descriptor = new ApkTool().createSingleFileDescriptor(type);
                descriptor.setTitle(ResourceTool.instance().getString("apkSelectTitle"));
                VirtualFile fileToSelect = ProjectManager.getInstance().getOpenProjects()[0].getBaseDir();

                FileChooser.chooseFiles(descriptor, null, fileToSelect, new FileChooser.FileChooserConsumer() {
                    @Override
                    public void cancelled() {  }

                    @Override
                    public void consume(java.util.List<VirtualFile> virtualFiles) {
                        String filePath = virtualFiles.get(0).getPath();
                        File file = new File(filePath);
                        selectApkBtn.setText(file.getAbsolutePath());
                        apkPath= file.getAbsolutePath();

                    }
                });
            }
        });

        getAppsBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                loadApiToken( false);
                currentPage= 1;
                allApps.clear();
                getData(currentPage) ; // 失败后重新手动获取
            }
        });

        loadApiToken( true); //
    }


    private void loadApiToken( boolean isInit){
        String filePath ="C://MySave.txt";
        String tokenKey ="apitoken" ;
        if(!isInit){
            File file = new File(filePath);
            if(!file.exists()){
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            StoreTool.properties_store(file.getAbsolutePath(),
                    tokenKey ,
                    getApiTokenStr() );
        }

        Properties prop = new Properties();
        try {
            prop.load(new FileReader(filePath ));
            Set<String> set = prop.stringPropertyNames();
            for (String key: set) {
                if(tokenKey.equals(key)){
                    apitokenFiled.setText( prop.getProperty(key) );
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private  String apkPath ;
    private Apps.ItemsBean selectedApp ;

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JPanel apkInfoPanel;
    private JLabel infoShow;
    private JLabel label4;
    private JTextField apitokenFiled;
    private JButton getAppsBtn;
    private JScrollPane scrollPane3;
    private JList applistABC;
    private JLabel appSum;
    private JLabel selectedProgram;
    private JLabel label2;
    private JButton selectApkBtn;
    private JLabel label3;
    private JScrollPane scrollPane2;
    private JTextArea updateLog;
    // JFormDesigner - End of variables declaration  //GEN-END:variables


    public JPanel getApkInfoPanel() {
        return apkInfoPanel;
    }


    public String getUpdateLog() {
        return updateLog.getText();
    }

    public String getApkPath() {
        return apkPath;
    }

    public Apps.ItemsBean getSelectedApp() {
        return selectedApp;
    }

    public boolean isApkReady(){
        String bundleID = getSelectedApp()==null ? null :getSelectedApp().getBundle_id();
        String apkPath =getApkPath() ;
        boolean isRead =bundleID!=null && apkPath!=null ;
        if(!isRead){
            infoShow.setText("请先选择项目和本地apk文件");
        }
        return isRead ;
    }





    public String getApiTokenStr(){
        return apitokenFiled.getText();
    }

    private void getData(int page){
        infoShow.setText("正在加载数据...page="+page);
        String api_token =  getApiTokenStr();
        String url = IpConfig.API_GETAPPS.replace("{api_token}" ,api_token ) ;
        url=url.replace("{page}",String.valueOf(page)) ;

        final String URLA=  url;
        new Thread(new Runnable() {
            @Override
            public void run() {
                new NetTool().get(URLA ,httpRespondCallback); ;
            }
        }).start();

    }


    private HttpRespondCallback httpRespondCallback = new HttpRespondCallback() {
        @Override
        public void onGetInfo(String msg, boolean hasError) {
            WkLog.showMsg(hasError+"  "+msg);

            if(hasError){
                infoShow.setText("apps访问异常 "+msg);
                return;
            }

            Apps apps = JSON.parseObject(msg, Apps.class);
            List<Apps.ItemsBean> items = apps.getItems();
            if(items==null){
                infoShow.setText("数据解析异常"+msg);
                return;
            }
            addAppToList(items) ;
            // fir 的api 固定死了，不能更改pagesize， 每次最多返回20条数据
            if(items.size() >= 20 ){
                currentPage++ ;
                getData(currentPage) ;// 继续去获取数据
            }else{
                infoShow.setText("加载完成");
                setApps(allApps);
            }
        }
    };

    private List<Apps.ItemsBean> appList ;
    private void setApps(List<Apps.ItemsBean> items){
        this.appList = items ;
        appSum.setText("总数="+String.valueOf(appList.size()));
        DefaultListModel dlm = new DefaultListModel();
        for(Apps.ItemsBean app : items){
            dlm.addElement(app.getName() +"   （"+ app.getBundle_id()+" ）");
        }
        applistABC.setModel(dlm);
    }

    private int currentPage =1 ;
    private List<Apps.ItemsBean> allApps= new ArrayList<>() ;
    private void addAppToList( List<Apps.ItemsBean> items){
        allApps.addAll(items) ;
    }
}
